

import java.util.ArrayList;



public class CallExpr extends PrimaryExpr {

	String id;
	ActualParams actual;

	public CallExpr(String id, ActualParams actual) {
		super();
		this.id = id;
		this.actual = actual;
	}

	public void check() throws SemanticException {
		SymbolTable table = SymbolTable.getInstance();
		// check that the method name exist
		if (table.get(id) == null || table.get(id).category != Entry.METHOD)
			throw new SemanticException("Method doesn't exist: " + id);
		// check that the parameters match the method definition
		ArrayList<Integer> formalParams = table.get(id).paramsType;
		// if empty
		if (actual == null) {
			if (formalParams.size() != 0)
				throw new SemanticException(
						"Actual params doesn't match formal params in length "
								+ id);
			return;
		}
		// System.out.println("actual " + actual);
		// if not same length
		ArrayList<Expression> actualParams = actual.getParamsList();
		if (actualParams.size() != formalParams.size()) {
			System.out.println("actual size " + actualParams.size()
					+ " , formal size " + formalParams.size());
			throw new SemanticException(
					"Actual params doesn't match formal params in length " + id);
		}

		// if not same types
		for (int i = 0; i < formalParams.size(); i++)
			if (formalParams.get(i) != actualParams.get(i).checkType())
				throw new SemanticException(
						"Actual params doesn't match formal params in type "
								+ id);
	}

	public int checkType() throws SemanticException {
		Entry e = SymbolTable.getInstance().get(id);
		return e.type;
	}

	public String toString() {
		String ret = "CallExpr " + id + "\n";
		if (actual != null) {
			String s = actual.toString();
			for (String st : s.split("\n"))
				ret += "| " + st + "\n";
		}
		return ret;
	}
}